function getQueryVariable(variable) {
    if (!window.location.search) return null;
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) return pair[1];
    }
    return false;
}

function toAgeNumber(date, estimate, extra) {
    if (!date) return undefined;
    date = date.split('-');
    let y = parseInt(date[0]),
        m = parseInt(date[1]),
        d = parseInt(date[2]);
    if (isNaN(y) || isNaN(m) || isNaN(d)) return 'none';
    let num = estimate & 1;
    num = (num << 13) | (y & 8191);
    num = (num << 4) | (m & 15);
    num = (num << 5) | (d & 31);
    num = (num << 9) | (extra & 511);
    return num;
}

const prefixZero = (num, n) => (Array(n).join(0) + num).slice(-n);

function toAgeData(num) {
    let e = (num = num >>> 0) & ((1 << 9) - 1);
    let d = (num = num >>> 9) & ((1 << 5) - 1);
    let m = (num = num >>> 5) & ((1 << 4) - 1);
    let y = (num = num >>> 4) & ((1 << 13) - 1);
    let estimate = (num = num >>> 13) & 1;
    const p = prefixZero;
    let r = {
        isEstimate: !!estimate,
        y: y,
        m: m,
        d: d,
        extra: estimate ? e : 0,
        date: `${p(y,4)}-${p(m,2)}-${p(d,2)}`,
        extraYear: estimate ? e / 12 | 0 : 0,
        extraMonth: estimate ? e % 12 : 0,
        result: () => {
            let age = getAge([y - r.extraYear, m - r.extraMonth, d]);
            for (let index in age)
                if (age[index] < 0) return '还未出生哦';
            let result = '';
            if (age[0] > 0) result = age[0] + ' 岁 ';
            if ((age[0] <= 1 || !estimate) && age[1] > 0) {
                if (result && age[1] < 10 && (estimate || age[2] == 0)) result += '零 ';
                result += age[1] + ' 个月 ';
            }
            if (!estimate && age[2] > 0) {
                if (result && age[2] < 10) result += '零 ';
                result += `${age[2]} 天`;
            }
            return (result || '今天').trim();
        }
    }
    return r;
}

/**
 * 计算实际年龄，精确到天
 * @param {*} birthday array [year, month, day]
 * @return array
 */
function getAge(birthday) {
    let date = new Date();
    let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
    let age = today.map((value, index) => {
        return value - birthday[index];
    });
    if (age[2] < 0) {
        let lastMonth = new Date(today[0], today[1], 0);
        age[1]--;
        age[2] += lastMonth.getDate();
    }
    if (age[1] < 0) {
        age[0]--;
        age[1] += 12;
    }
    return age;
}
/**
 * 解析日期
 * @param date 日期数据/年龄数据
 * @return 日期/年龄
 * */
function parseDate(date) {
    if (isNaN(date)) {
        date = new Date(date);
        const p = prefixZero;
        return `${p(date.getFullYear(),4)}-${p(date.getMonth() + 1,2)}-${p(date.getDate(),2)}`;
    } else return toAgeData(date).result();
}

/**
 * 构建html图标
 * @param name 图标名称
 * @param clazz 附加类
 * @param id 附加ID
 * */
function icon(name, color = '', size = '', clazz = '', id) {
    if (Array.isArray(clazz)) clazz = clazz.join(' ');
    if (clazz) clazz = ' ' + clazz;
    if (!name.startsWith('icon-')) name = 'icon-' + name;
    if (color) color = `color: ${color};`;
    if (size) size = `font-size: ${size};`;
    return `<svg class="icon${clazz}"${id?`id="${id}"`:''} style="${color}${size}" aria-hidden="true"><use xlink:href="#${name}"></use></svg>`
}

/**
 * 上传文件
 * */
function uploadFile(target, url, beforeSend, afterSend) {

    let files = (typeof target === 'string' ? document.getElementById(target) : target).files;
    files = files ? [...files] : [target];console.log(files);
    files.forEach(file => {
        if (!file) return alert("未选中任何文件");
        var fr = new FileReader();
        fr.onload = () => {
            $.ajax({
                type: "POST",
                url: `/upload/${url}`,
                cache: 'false',
                contentType: 'application/file',
                data: fr.result,
                beforeSend: req => {
                    beforeSend && beforeSend(req);
                    req.setRequestHeader("x-access-token", localStorage.getItem("token"));
                    req.setRequestHeader("x-file-size", file.size);
                    req.setRequestHeader("x-file-type", file.type);
                    req.setRequestHeader("Connection", 'keep-alive');
                    req.setRequestHeader("Content-Type", 'application/octet-stream');
                },
                success: r => {
                    if (afterSend && afterSend(r)) return;
                    if (r.success) (files.length>3?console.log:alert)('成功上传, 编号:\n' + r.result);
                    else alert('出错: ' + r.err);
                }
            });
        };
        fr.readAsBinaryString(file);
    });
}